package com.zjitc.controller;

import com.zjitc.common.ServerResponse;
import com.zjitc.pojo.Car;
import com.zjitc.pojo.Caritem;
import com.zjitc.vo.Msg;
import com.zjitc.pojo.User;
import com.zjitc.service.CarService;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * Create By IntelliJ IDEA
 *
 * @author: myq
 * @create-Time: 2017/11/20  16:59
 */
@Controller
@RequestMapping("/car")
public class CarController {

  @Autowired
  private CarService service;

  private static final String USER = "user";

  @RequestMapping(value = "/add2cart",method = RequestMethod.POST)
  @ResponseBody
  public ServerResponse cart(HttpSession session, HttpServletRequest request, String pid,
      Integer count) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    Object o = session.getAttribute(USER);
    if (o == null) {
      String msg = "未检测到用户，请先登录";
      String address = request.getContextPath() + "jsp/login";
      Msg ms = new Msg(msg, address);
      return ServerResponse.createError(ms);
    } else {
      User user = (User) o;
      service.add2car(user.getUid(), count, pid);
      return ServerResponse.createSuccess("0");
    }
  }

  @RequestMapping("/showcar")
  public ModelAndView show(HttpSession session) throws ServletException, IOException {
    User user = (User) session.getAttribute(USER);
    List<Caritem> items = service.findAll(user.getUid());
    double total = 0.0;
    for (Caritem caritem : items) {
      total += caritem.getPrice();
    }
    ModelAndView mv = new ModelAndView();
    mv.addObject("items", items);
    mv.addObject("total", total);
    mv.setViewName("jsp/cart");
    return mv;
  }

  @RequestMapping("/deletecar")
  public ModelAndView delete(String uid) throws ServletException, IOException {
    ModelAndView modelAndView = new ModelAndView();
    int success = service.deleteAll(uid);
    modelAndView.setViewName("redirect:/car/showcar.do");
    return modelAndView;
  }

  @RequestMapping("/deletesingle")
  @ResponseBody
  public ServerResponse<Car> deletesingle(@RequestParam("uid") String uid,
      @RequestParam("pid") String pid) throws ServletException, IOException {
    return service.deletesingle(pid, uid);
  }
}
